{% extends "base.html" %}

{% block content %}
<div class="container mt-4">
    <div class="row">
        <!-- 左侧分类列表 -->
        <div class="col-md-3">
            <div class="card ink-card mb-4">
                <div class="card-header ink-header">
                    <h5 class="mb-0">图书分类</h5>
                </div>
                <div class="list-group list-group-flush">
                    <a href="{{ url_for('books') }}" class="list-group-item list-group-item-action {% if not request.args.get('category') %}active{% endif %}">
                        全部分类
                    </a>
                    {% for category in categories %}
                    <a href="{{ url_for('books', category=category.id) }}" 
                       class="list-group-item list-group-item-action {% if request.args.get('category')|int == category.id %}active{% endif %}">
                        {{ category.name }}
                    </a>
                    {% endfor %}
                </div>
            </div>
        </div>

        <!-- 右侧图书列表 -->
        <div class="col-md-9">
            <div class="row row-cols-1 row-cols-md-3 g-4">
                {% for book in books.items %}
                <div class="col">
                    <div class="card h-100 ink-card">
                        {% if book.cover_path %}
                        <img src="{{ url_for('static', filename='covers/' + book.cover_path) }}" 
                             class="card-img-top book-cover" alt="{{ book.title }}" 
                             data-default-cover="{{ url_for('static', filename='covers/default_cover.jpg') }}"
                             onerror="this.onerror=null; this.src=this.getAttribute('data-default-cover')">
                        {% else %}
                        <img src="{{ url_for('static', filename='covers/default_cover.jpg') }}" 
                             class="card-img-top book-cover" alt="{{ book.title }}">
                        {% endif %}
                        <div class="card-body">
                            <h5 class="card-title">{{ book.title }}</h5>
                            <h6 class="card-subtitle mb-2 text-muted">{{ book.author }}</h6>
                            <p class="card-text">{{ book.description[:100] }}...</p>
                            <div class="d-flex justify-content-between align-items-center">
                                <small class="text-muted">
                                    <i class="fas fa-eye"></i> {{ book.views }} 次浏览
                                </small>
                                <div class="btn-group">
                                    <a href="{{ url_for('view_book', book_id=book.id) }}" class="btn btn-sm btn-outline-primary">
                                        <i class="fas fa-book-open"></i> 阅读
                                    </a>
                                    <a href="{{ url_for('download_book', book_id=book.id) }}" class="btn btn-sm btn-outline-success">
                                        <i class="fas fa-download"></i> 下载
                                    </a>
                                    <button class="btn btn-sm btn-outline-danger favorite-btn" data-book-id="{{ book.id }}" data-bs-toggle="tooltip" data-bs-placement="top" title="{% if book in current_user.favorite_books %}取消收藏{% else %}收藏此书{% endif %}">
                                        <i class="{% if book in current_user.favorite_books %}fas fa-heart{% else %}far fa-heart{% endif %}"></i>
                                    </button>
                                </div>
                            </div>
                        </div>
                        <div class="card-footer text-muted">
                            <small>上传于 {{ book.created_at.strftime('%Y-%m-%d') }}</small>
                        </div>
                    </div>
                </div>
                {% endfor %}
            </div>

            <!-- 分页 -->
            {% if books.pages > 1 %}
            <nav class="mt-4">
                <ul class="pagination justify-content-center">
                    {% for page in books.iter_pages() %}
                        {% if page %}
                            <li class="page-item {% if page == books.page %}active{% endif %}">
                                <a class="page-link" href="{{ url_for('books', page=page, category=request.args.get('category')) }}">
                                    {{ page }}
                                </a>
                            </li>
                        {% else %}
                            <li class="page-item disabled">
                                <span class="page-link">...</span>
                            </li>
                        {% endif %}
                    {% endfor %}
                </ul>
            </nav>
            {% endif %}
        </div>
    </div>
</div>

<style>
.book-cover {
    height: 200px;
    object-fit: cover;
    border-top-left-radius: 10px;
    border-top-right-radius: 10px;
}

.book-cover-placeholder {
    height: 200px;
    background-color: #f8f9fa;
    border-top-left-radius: 10px;
    border-top-right-radius: 10px;
}

.ink-card {
    transition: transform 0.3s ease;
}

.ink-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 10px 20px rgba(0,0,0,0.1);
}

.favorite-btn {
    transition: all 0.3s ease;
    position: relative;
    overflow: hidden;
    border-width: 1.5px;
}

.favorite-btn:hover {
    transform: scale(1.1);
    box-shadow: 0 2px 5px rgba(220, 53, 69, 0.2);
}

.favorite-btn .fas.fa-heart {
    color: #dc3545;
}

.favorite-btn .far.fa-heart {
    transition: transform 0.3s ease, color 0.3s ease;
}

.favorite-btn:hover .far.fa-heart {
    color: #dc3545;
    transform: scale(1.2);
}

.favorite-btn::after {
    content: '';
    position: absolute;
    top: 50%;
    left: 50%;
    width: 5px;
    height: 5px;
    background: rgba(220, 53, 69, 0.3);
    opacity: 0;
    border-radius: 100%;
    transform: scale(1, 1) translate(-50%);
    transform-origin: 50% 50%;
}

.favorite-btn:focus:not(:active)::after {
    animation: ripple 1s ease-out;
}

@keyframes ripple {
    0% {
        transform: scale(0, 0);
        opacity: 0;
    }
    20% {
        transform: scale(25, 25);
        opacity: 0.3;
    }
    100% {
        opacity: 0;
        transform: scale(40, 40);
    }
}
</style>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // 初始化工具提示
    var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'))
    var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
        return new bootstrap.Tooltip(tooltipTriggerEl)
    });
    
    // 为所有收藏按钮添加点击事件监听器
    document.querySelectorAll('.favorite-btn').forEach(function(btn) {
        btn.addEventListener('click', function(event) {
            event.preventDefault();
            const bookId = this.getAttribute('data-book-id');
            toggleFavorite(bookId, this);
        });
    });
});

function toggleFavorite(bookId, button) {
    // 添加点击反馈
    button.classList.add('active');
    
    fetch(`/book/${bookId}/favorite`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        credentials: 'same-origin'
    })
    .then(response => response.json())
    .then(data => {
        const icon = button.querySelector('i');
        const tooltip = bootstrap.Tooltip.getInstance(button);
        
        if (data.action === 'favorited') {
            // 添加动画效果
            icon.classList.add('animate__animated', 'animate__heartBeat');
            
            // 移除旧图标，添加新图标
            icon.classList.remove('far');
            icon.classList.add('fas');
            
            // 更新工具提示
            button.setAttribute('data-bs-original-title', '取消收藏');
            tooltip.update();
            
            showToast('收藏成功', '图书已添加到您的收藏');
        } else {
            // 添加取消动画
            icon.classList.add('animate__animated', 'animate__fadeOut');
            
            setTimeout(() => {
                icon.classList.remove('animate__fadeOut');
                icon.classList.remove('fas');
                icon.classList.add('far');
                icon.classList.add('animate__fadeIn');
                
                setTimeout(() => {
                    icon.classList.remove('animate__fadeIn');
                }, 500);
            }, 300);
            
            // 更新工具提示
            button.setAttribute('data-bs-original-title', '收藏此书');
            tooltip.update();
            
            showToast('已取消收藏', '图书已从您的收藏中移除');
        }
        
        // 移除active状态
        setTimeout(() => {
            button.classList.remove('active');
        }, 200);
    })
    .catch(error => console.error('Error:', error));
}

// 显示提示信息
function showToast(title, message) {
    // 创建toast元素
    const toastEl = document.createElement('div');
    toastEl.className = 'toast align-items-center text-white bg-primary border-0';
    toastEl.setAttribute('role', 'alert');
    toastEl.setAttribute('aria-live', 'assertive');
    toastEl.setAttribute('aria-atomic', 'true');
    
    // 设置自动隐藏
    toastEl.setAttribute('data-bs-delay', '3000');
    
    // 添加内容
    toastEl.innerHTML = `
        <div class="d-flex">
            <div class="toast-body">
                <strong>${title}</strong>: ${message}
            </div>
            <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button>
        </div>
    `;
    
    // 添加到页面
    const toastContainer = document.querySelector('.toast-container');
    if (toastContainer) {
        toastContainer.appendChild(toastEl);
    } else {
        // 如果不存在容器则创建
        const newContainer = document.createElement('div');
        newContainer.className = 'toast-container position-fixed bottom-0 end-0 p-3';
        newContainer.appendChild(toastEl);
        document.body.appendChild(newContainer);
    }
    
    // 显示toast
    const toast = new bootstrap.Toast(toastEl);
    toast.show();
}
</script>

<!-- 添加animate.css库提供动画效果 -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css" />
{% endblock %} 